<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- Table Header -->
      <div class="table-header">
        <!-- 右侧 学年选择和学期选择 -->
        <div style="display: flex; flex-direction: column; width: 25%">
          <div class="center">
            <el-button @click="curNumPre" size="mini" :disabled="curNum === 1">
              <i class="el-icon-arrow-left"></i>上一个
            </el-button>
            <p>
              {{ curNum.toString().padStart(2, '0') }} /
              {{
                allCurriculumsLength === 0 ? '♾️' : allCurriculumsLength.toString().padStart(2, '0')
              }}
            </p>
            <el-button @click="curNumNext" size="mini" :disabled="curNum === allCurriculumsLength">
              <i class="el-icon-arrow-right"></i>下一个
            </el-button>
          </div>
          <el-slider
            v-model="_curNum"
            :step="1"
            show-stops
            :min="1"
            :max="allCurriculumsLength || 1"
            :disabled="allCurriculumsLength === 0"
          />
        </div>
        <!-- 左侧 日期和显示详细 -->
        <div style="display: flex; flex-direction: column; align-items: center">
          <el-tag type="info">{{
            currentWeekRange.includes('NaN-NaN-NaN')
              ? '-----------------------'
              : currentWeekRange[0] + '至' + currentWeekRange[1]
          }}</el-tag>
          <el-switch
            v-model="showDetails"
            active-text="显示详细"
            inactive-text="隐藏详细"
            size="small"
          />
          <el-switch
            v-model="showCurrentWeek"
            active-text="显示全部"
            inactive-text="只看当前"
            size="small"
          />
          <el-button type="primary" @click="dialogVisible = true" style="width: 100%">
            更新排课结果</el-button
          >
        </div>
        <!-- 中间 周数和周数选择 -->
        <div
          style="display: flex; flex-direction: column; width: 25%"
          v-if="allCurriculumsLength !== 0 && !showCurrentWeek"
        >
          <div class="center">
            <el-button @click="weekPre" size="mini" :disabled="weekNum === 1">
              <i class="el-icon-arrow-left"></i>上一周
            </el-button>
            <p>
              {{ currentYear }}年{{ currentMonth.toString().padStart(2, '0') }}月 第{{
                weekNum.toString().padStart(2, '0')
              }}周
            </p>
            <el-button @click="weekNext" size="mini" :disabled="weekNum === 20">
              下一周<i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <el-slider v-model="_weekNum" :step="1" show-stops :min="1" :max="20" />
        </div>
        <div style="display: flex; flex-direction: column; width: 25%" v-else-if="!showCurrentWeek">
          <el-tag type="info">无结果</el-tag>
        </div>
        <div style="display: flex; flex-direction: column; width: 25%" v-else></div>
      </div>
      <hr style="margin: 0" />
      <!-- 课表表格 -->
      <table v-if="allCurriculumsLength !== 0">
        <thead style="height: 50px">
          <tr>
            <th class="fixed-width-header">时间</th>
            <th v-for="(day, index) in weekDays" :key="index" class="fixed-width-header">
              {{ day }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
            <td class="time fixed-width">{{ row.time }}</td>
            <td
              v-for="(day, dayIndex) in weekDays"
              :key="dayIndex"
              class="fixed-width"
              @click="rainbow ? (rainbow = false) : (rainbow = true)"
            >
              <el-popover
                v-if="getCourseContent(row, day)"
                placement="top"
                width="auto"
                trigger="click"
                hide-after="100"
              >
                <template #reference>
                  <div
                    class="course-item"
                    :class="{
                      'not-current-week':
                        !isCurrentWeek(getCourseContent(row, day)) && !showCurrentWeek,
                      'rainbow-border': getCourseContent(row, day).some(
                        item => selected_course_names.includes(item.course_name.trim()) && rainbow
                      ),
                    }"
                    :style="{
                      '--dynamic-bg-color': getColorByCourseName(
                        getCourseContent(row, day)[0]?.course_name
                      ),
                      backgroundColor: getColorByCourseName(
                        getCourseContent(row, day)[0]?.course_name
                      ),
                    }"
                    style="height: 100%"
                  >
                    <p>{{ formatCourseContent(getCourseContent(row, day)) }}</p>
                  </div>
                </template>
                <div class="popover-content">
                  <div v-for="content in getCourseContent(row, day)" :key="content.course_name">
                    <h2 style="margin-left: 2px">{{ content.course_name }}</h2>
                    <strong style="margin-left: 2px">教学班:</strong> {{ content.course_code
                    }}<br />
                    <strong style="margin-left: 2px">任课老师:</strong> {{ content.course_teacher
                    }}<br />
                    <template v-for="room in content.course_week_room">
                      <el-tag
                        type="success"
                        effect="dark"
                        :style="{
                          borderRadius: '50px',
                          marginRight: '5px',
                          marginBottom: '2px',
                          marginTop: '5px',
                        }"
                      >
                        {{ room.course_room }}
                      </el-tag>
                      <el-tag
                        type="info"
                        effect="dark"
                        :style="{
                          borderRadius: '50px',
                          marginRight: '5px',
                          marginBottom: '2px',
                          marginTop: '5px',
                        }"
                      >
                        {{ room.course_weeks.join(', ') }}
                      </el-tag>
                      <br />
                    </template>
                    <hr
                      style="height: 1.5px; border-width: 0; color: gray; background-color: gray"
                    />
                  </div>
                </div>
              </el-popover>
            </td>
          </tr>
        </tbody>
      </table>
      <template v-else>
        <el-empty :image-size="200" description="还未获取到课表数据" />
      </template>
    </el-card>

    <!-- 更新课表对话框 -->
    <el-dialog title="排课计算" v-model="dialogVisible" width="25%" center>
      <el-form>
        <!-- 禁止时间段 -->
        <el-form-item label="禁止时间段">
          <el-input
            v-model="forbiddenDisplay"
            readonly
            placeholder="点击选择需要排除的时间段（可选）"
            @click="showTimePicker('forbidden')"
          >
          </el-input>
        </el-form-item>

        <!-- 允许时间段 -->
        <el-form-item label="允许时间段">
          <el-input
            v-model="allowedDisplay"
            readonly
            placeholder="点击选择特别允许的时间段（可选）"
            @click="showTimePicker('allowed')"
          >
          </el-input>
        </el-form-item>

        <!-- 教学班代码 -->
        <el-form-item label="指定教学班">
          <el-cascader
            v-model="selectedCourseCodes"
            :options="courseOptions"
            :props="{ multiple: true, checkStrictly: true }"
            placeholder="请选择指定教学班（可选）"
            style="width: 100%"
            @change="updateCourseCodes"
            filterable
          />
          <div style="margin-top: 10px">
            <el-tag
              v-for="(code, index) in config.courseCodes"
              :key="code"
              style="margin-right: 5px"
            >
              {{ code }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 是否排必修 -->
        <el-form-item label="是否排必修">
          <el-switch
            v-model="config.is_biXiu"
            active-text="排必修"
            inactive-text="不排必修"
            @change="fetchSelectCode"
          />
        </el-form-item>
      </el-form>

      <!-- 时间选择对话框 -->
      <el-dialog :title="timePickerTitle" v-model="showTimeDialog" width="70%" append-to-body>
        <div class="time-grid">
          <div class="header-row">
            <div class="header-cell"></div>
            <div class="header-cell" v-for="day in 7" :key="day">
              周{{ ['一', '二', '三', '四', '五', '六', '日'][day - 1] }}
            </div>
          </div>
          <div class="time-row" v-for="section in 8" :key="section">
            <div class="row-header">{{ TimeMap[`T${section}`] }}</div>
            <div
              class="time-cell"
              v-for="day in 7"
              :key="day"
              :class="{ selected: isSelected(day, section) }"
              @click="toggleTime(day, section)"
            >
              {{ selectedLabels(day, section) }}
            </div>
          </div>
        </div>
        <template #footer>
          <el-button @click="showTimeDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmTimeSelection">确定</el-button>
        </template>
      </el-dialog>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            v-loading.fullscreen.lock="fullscreenLoading"
            @click="fetchSchedule"
            >更新排课</el-button
          >
          <el-button @click="clearConfig">清空</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, reactive } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import api from '../axios/api'
import { encrypt, decrypt } from '../utils/crypto'
import { useTimetableGenerator } from './generate'
import { parse } from '@babel/parser'
const { generate, validSchedules, allCurriculums } = useTimetableGenerator()

const weekDays = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日'])
const tableData = ref([]) // 课表数据
const weekNum = ref(1) // 当前周数
const _weekNum = ref(1) // 当前周数
const curNum = ref(1) // 当前课表
const _curNum = ref(1) // 当前课表
const allCurriculumsLength = ref(0) // 所有课表长度
const firstWeekDate = ref('') // 课表第一周日期
const currentYear = ref('') // 当前年份
const currentMonth = ref('') // 当前月份
const currentWeekRange = ref([]) // 当前星期范围
const showDetails = ref(false) // 是否显示详细
const showCurrentWeek = ref(true) // 是否只看当前周
const dialogVisible = ref(true) // 是否显示对话框
const fullscreenLoading = ref(false) // 是否全屏加载
const rainbow = ref(true) // 是否彩虹
// 原始数据结构（根据实际数据结构初始化）
const TimeMap = ref({
  T1: '1 - 2 节\r\n09:00 - 10:20',
  T2: '3 - 4 节\r\n10:40 - 12:00',
  T3: '5 - 6 节\r\n12:30 - 13:50',
  T4: '7 - 8 节\r\n14:00 - 15:20',
  T5: '9 - 10 节\r\n15:30 - 16:50',
  T6: '11 - 12 节\r\n17:00 - 18:20',
  T7: '13 - 14 节\r\n19:00 - 20:20',
  T8: '15 - 16 节\r\n20:30 - 21:50',
})
const colorList = [
  '#252322',
  '#74663b',
  '#783930',
  '#ae4137',
  '#7f7063',
  '#424458',
  '#12203B',
  '#DE7A60',
  '#F4A261',
  '#9BC1BC',
  '#5D576B',
  '#344E41',
]

const colorMap = {} // 用于存储课程名称和颜色的映射关系
let colorIndex = 0 // 当前分配的颜色索引

const getColorByCourseName = courseName => {
  if (!colorMap[courseName]) {
    // 如果课程名称没有分配颜色，从颜色列表中分配一个
    colorMap[courseName] = colorList[colorIndex % colorList.length]
    colorIndex++ // 分配下一个颜色
  }
  return colorMap[courseName]
}

const roomColorMap = {} // 用于存储上课地点和颜色的映射关系
let roomColorIndex = 0 // 当前分配的颜色索引

const getColorByRoom = room => {
  if (!roomColorMap[room]) {
    // 如果上课地点没有分配颜色，从颜色列表中分配一个
    roomColorMap[room] = colorList[roomColorIndex % colorList.length]
    roomColorIndex++ // 分配下一个颜色
  }
  return roomColorMap[room]
}

// 加载课表数据
const loadSchedule = () => {
  const selectedData = allCurriculums.value[curNum.value - 1]
  if (selectedData) {
    tableData.value = selectedData.schedules
    if (selectedData.week_info) {
      firstWeekDate.value = new Date(
        selectedData.week_info.week_start_date.replace(/年|月/g, '-').replace('日', '')
      )
    } else {
      firstWeekDate.value = new Date()
    }
    initData(firstWeekDate.value)
  } else {
    ElMessage.warning('所选的课程与课表数据完全冲突！')
  }
}

// 格式化日期
const formatDate = (year, month, day) => {
  const y = year
  let m = month < 10 ? `0${month}` : month
  let d = day < 10 ? `0${day}` : day
  return `${y}-${m}-${d}`
}

// 初始化数据
const initData = cur => {
  const date = cur ? new Date(cur) : new Date()
  const currentDay = date.getDate()
  currentYear.value = date.getFullYear()
  currentMonth.value = date.getMonth() + 1
  const currentWeek = date.getDay() || 7

  const str = formatDate(currentYear.value, currentMonth.value, currentDay)
  const days = []

  // 计算当前一周的日期
  for (let i = currentWeek - 1; i >= 0; i--) {
    const d = new Date(str)
    d.setDate(d.getDate() - i)
    days.push(d)
  }

  for (let i = 1; i <= 7 - currentWeek; i++) {
    const d = new Date(str)
    d.setDate(d.getDate() + i)
    days.push(d)
  }

  // 更新当前星期范围
  currentWeekRange.value = [
    formatDate(days[0].getFullYear(), days[0].getMonth() + 1, days[0].getDate()),
    formatDate(days[6].getFullYear(), days[6].getMonth() + 1, days[6].getDate()),
  ]

  if (!showCurrentWeek.value) {
    // 将日期信息添加到 weekDays 中
    const dataArr = days.map(item => `${item.getMonth() + 1}/${item.getDate()}`)
    weekDays.value = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'].map(
      (day, index) => `${day}(${dataArr[index]})`
    )
  } else {
    weekDays.value = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  }

  // 计算当前 cur 是 firstWeekDate 的第几周
  const diffTime = cur - firstWeekDate.value
  if (diffTime < 0) {
    weekNum.value = 0
  } else {
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    weekNum.value = Math.floor(diffDays / 7) + 1
  }
}

watch(showCurrentWeek, newVal => {
  initData(firstWeekDate.value)
})

const weekPre = () => {
  _weekNum.value = weekNum.value - 1
  const d = new Date(currentWeekRange.value[0])
  d.setDate(d.getDate() - 7)
  initData(d)
}
const weekNext = () => {
  _weekNum.value = weekNum.value + 1
  const d = new Date(currentWeekRange.value[1])
  d.setDate(d.getDate() + 7)
  initData(d)
}
// 监听_weekNum的变化，并模拟 weekPre 和 weekNext
watch(_weekNum, newVal => {
  if (newVal < weekNum.value) {
    weekPre()
  } else if (newVal > weekNum.value) {
    weekNext()
  }
})

const curNumPre = () => {
  if (curNum.value > 1) {
    curNum.value -= 1
    _curNum.value = curNum.value
  }
  loadSchedule()
}

const curNumNext = () => {
  if (curNum.value < allCurriculumsLength.value) {
    curNum.value += 1
    _curNum.value = curNum.value
  }
  loadSchedule()
}

// 监听_curNum的变化，并模拟 curNumPre 和 curNumNext
watch(_curNum, newVal => {
  if (newVal < curNum.value) {
    curNumPre()
  } else if (newVal > curNum.value) {
    curNumNext()
  }
})

// 更新课程内容
const getCourseContent = (row, day) => {
  const dayMap = {
    周一: 'monday',
    周二: 'tuesday',
    周三: 'wednesday',
    周四: 'thursday',
    周五: 'friday',
    周六: 'saturday',
    周日: 'sunday',
  }
  const key = dayMap[day.split('(')[0]] // 去掉日期部分，只保留星期
  return row[key]
}

// 周次格式化
const formatWeeks = weeks => {
  // 转成数字
  weeks = weeks.map(Number)
  if (weeks.length === 0) return ''
  if (weeks.length === 1) return `第${weeks[0]}周`

  // 对周次进行排序
  weeks.sort((a, b) => a - b)

  const isSingleWeek = weeks.every((week, index, arr) => {
    // 如果是第一个元素则跳过
    if (index === 0) return true
    // 判断是否为连续单周
    return week === arr[index - 1] + 2 && arr[index - 1] % 2 === 1
  })

  const isDoubleWeek = weeks.every((week, index, arr) => {
    // 如果是第一个元素则跳过
    if (index === 0) return true
    // 判断是否为连续双周
    return week === arr[index - 1] + 2 && arr[index - 1] % 2 === 0
  })

  const start = weeks[0]
  const end = weeks[weeks.length - 1]

  if (isSingleWeek) {
    return `${start}-${end}周（单周）`
  } else if (isDoubleWeek) {
    return `${start}-${end}周（双周）`
  } else if (weeks.length === end - start + 1) {
    return `${start}-${end}周`
  } else {
    return `第${weeks.join(',')}周`
  }
}

// 格式化课程内容
const formatCourseContent = contents => {
  if (!contents) return ''

  if (!showDetails.value) {
    // 删除为空的元素后，contents 列表内每一个元素的 course_name 用 、拼接
    const formattedCourses = contents
      .map(item => {
        if (
          item.course_week_room.some(weekRoom =>
            weekRoom.course_weeks.includes(weekNum.value.toString())
          ) ||
          showCurrentWeek.value
        ) {
          return item.course_name
        }
      })
      .filter(Boolean) // 过滤掉空值
    return formattedCourses.length >= 2
      ? formattedCourses.map(course => `【${course}】`).join('\n')
      : formattedCourses.join('\n')
  }
  const formattedCourses = contents
    .map(item => {
      if (
        item.course_week_room.some(weekRoom =>
          weekRoom.course_weeks.includes(weekNum.value.toString())
        ) ||
        showCurrentWeek.value
      ) {
        return `${item.course_name} (${item.course_code} ${
          item.course_teacher
        } ${item.course_week_room
          .map(weekRoom => weekRoom.course_weeks)
          .map(formatWeeks)
          .join('、')} ${item.course_week_room
          .map(weekRoom => weekRoom.course_room)
          .map(room => `[${room}]`)
          .join('、')})`
      }
    })
    .filter(Boolean) // 过滤掉空值
  return formattedCourses.length >= 2
    ? formattedCourses.map(course => `【${course}】`).join('\n')
    : formattedCourses.join('\n')
}

const isCurrentWeek = contents => {
  if (!contents) return false
  return contents.some(content =>
    content.course_week_room.some(weekRoom =>
      weekRoom.course_weeks.includes(weekNum.value.toString())
    )
  )
}

// 更新课表
const fetchSchedule = async () => {
  curNum.value = _curNum.value = 1
  weekNum.value = _weekNum.value = 1
  // 检查config.forbidden与config.allowed是否冲突
  if (config.forbidden.size > 0 && config.allowed.size > 0) {
    const forbidden = Array.from(config.forbidden)
    const allowed = Array.from(config.allowed)
    const conflict = forbidden.some(forbidden => allowed.includes(forbidden))
    if (conflict) {
      ElMessage.warning('禁止时间段和允许时间段冲突')
      return
    }
  }

  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  fullscreenLoading.value = true // 全屏加载

  try {
    await generate(config) // 使用 await 等待生成完成
    // console.log(allCurriculums.value)
    allCurriculumsLength.value = allCurriculums.value?.length || 0
    loadSchedule()
  } catch (error) {
    console.error('生成失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '未知错误')
  } finally {
    loading.close()
    fullscreenLoading.value = false
    dialogVisible.value = false
  }
}

const selected_course_data = ref()
const selected_course_names = ref([])
const curriculum = ref()
const emptyCurriculum = ref({
  week_info: {
    date: '2000年01月01日 星期六',
    week: '1',
    week_start_date: '2000年01月01日',
  },

  schedules: [
    {
      time: '1 - 2 节\n09:00 - 10:20',
      friday: '',
      monday: '',
      sunday: '',
      tuesday: '',
      saturday: '',
      thursday: '',
      wednesday: '',
    },
    {
      time: '3 - 4 节\n10:40 - 12:00',
      friday: '',
      monday: '',
      sunday: '',
      tuesday: '',
      saturday: '',
      thursday: '',
      wednesday: '',
    },
    {
      time: '5 - 6 节\n12:30 - 13:50',
      friday: '',
      monday: '',
      sunday: '',
      tuesday: '',
      saturday: '',
      thursday: '',
      wednesday: '',
    },
    {
      time: '7 - 8 节\n14:00 - 15:20',
      friday: '',
      monday: '',
      sunday: '',
      tuesday: '',
      saturday: '',
      thursday: '',
      wednesday: '',
    },
    {
      time: '9 - 10 节\n15:30 - 16:50',
      friday: '',
      monday: '',
      sunday: '',
      tuesday: '',
      saturday: '',
      thursday: '',
      wednesday: '',
    },
    {
      time: '11 - 12 节\n17:00 - 18:20',
      friday: '',
      monday: '',
      sunday: '',
      tuesday: '',
      saturday: '',
      thursday: '',
      wednesday: '',
    },
    {
      time: '13 - 14 节\n19:00 - 20:20',
      friday: '',
      monday: '',
      sunday: '',
      tuesday: '',
      saturday: '',
      thursday: '',
      wednesday: '',
    },
    {
      time: '15 - 16 节\n20:30 - 21:50',
      friday: '',
      monday: '',
      sunday: '',
      tuesday: '',
      saturday: '',
      thursday: '',
      wednesday: '',
    },
  ],
  year_term: {
    year: '2000',
    semester: '1',
  },
})

const fetchSelectCode = () => {
  selected_course_data.value = JSON.parse(localStorage.getItem('selected_course_data') || '{}')
  curriculum.value = JSON.parse(localStorage.getItem('selected_curriculum') || '{}')
  const uniqueCourses = extractUniqueCourseNames(curriculum.value)
  console.log(uniqueCourses)
  const courses = JSON.parse(localStorage.getItem('course_data') || '{}').Courses.map(course => ({
    Dept: course.Dept,
    Nature: course.Nature,
    Crd: course.Crd,
    Code: course.Code,
    Sim: course.Sim,
    Title: course.Title,
    Time: course.Time,
  }))

  if (config.is_biXiu) {
    // 排必修
    if (uniqueCourses.length > 0) {
      const selected_course_data_courses = selected_course_data.value.Courses
      uniqueCourses.forEach(course_name => {
        const course = courses.find(item => item.Title === course_name)
        if (course) {
          selected_course_data_courses.push(course) // 添加必修课
        }
      })
      selected_course_data.value.Courses = selected_course_data_courses
    }
    // 使用空白课表
    localStorage.setItem('generate_selected_curriculum', JSON.stringify(emptyCurriculum.value))
  } else {
    // 不排必修
    if (uniqueCourses.length > 0) {
      const selected_course_data_courses = selected_course_data.value.Courses
      uniqueCourses.forEach(course_name => {
        const course = courses.find(item => item.Title === course_name)
        if (course) {
          const index = selected_course_data_courses.indexOf(course)
          if (index > -1) {
            selected_course_data_courses.splice(index, 1) // 删除必修课
          }
        }
      })
      selected_course_data.value.Courses = selected_course_data_courses
    }
    // 使用原课表
    console.log(curriculum.value)
    localStorage.setItem('generate_selected_curriculum', JSON.stringify(curriculum.value))
  }
  localStorage.setItem('generate_selected_course_data', JSON.stringify(selected_course_data.value))

  selected_course_names.value = selected_course_data.value.Courses.map(course => course.Title)

  // 示例数据，假设课程名称和教学班代码的结构如下
  const courseOptionsData = selected_course_data.value.Courses.map(course => {
    // 使用 Set 去重教学班代码
    const classCodes = new Set()

    // 遍历所有时间段信息
    course.Time.forEach(timeBlock => {
      // 排除 timeBlock 中的 t 属性
      Object.keys(timeBlock).forEach(key => {
        if (key !== 't') {
          // 遍历每个时间段中的课程安排
          timeBlock[key].forEach(item => {
            classCodes.add(item.c_c.replace('01', ''))
          })
        }
      })
    })

    return {
      label: course.Title,
      value: course.Title,
      disabled: true,
      children: Array.from(classCodes).map(code => ({
        label: code,
        value: code,
        disabled: false,
      })),
    }
  })

  // 排序
  courseOptions.value = courseOptionsData.map(parent => ({
    ...parent,
    children: parent.children.sort((a, b) => a.value.localeCompare(b.value)),
  }))
  // console.log(JSON.stringify(courseOptions.value))
}

onMounted(() => {
  fetchSelectCode()
  fetchSchedule()
})

const showTimeDialog = ref(false)
const currentPickerType = ref('forbidden')
const tempSelection = ref(new Set())

// 修改后（响应式）
const config = reactive({
  forbidden: new Set(), // 禁止时间段
  allowed: new Set(), // 允许时间段
  courseCodes: [], // 教学班代码
  is_biXiu: false, // 是否排必修
})

const courseOptions = ref()
// 计算属性
const forbiddenDisplay = computed(() => {
  return config.forbidden.size ? `已排除 ${config.forbidden.size} 个时间段` : ''
})

const allowedDisplay = computed(() => {
  return config.allowed.size ? `已特别允许 ${config.allowed.size} 个时间段` : ''
})

const timePickerTitle = computed(() => {
  return currentPickerType.value === 'forbidden' ? '选择禁止时间段' : '选择允许时间段'
})

const initialForbidden = ref(new Set())
const initialAllowed = ref(new Set())
// 方法
const showTimePicker = type => {
  console.log(type)
  currentPickerType.value = type
  // 备份原始数据
  initialForbidden.value = new Set(config.forbidden)
  initialAllowed.value = new Set(config.allowed)
  tempSelection.value = new Set(config[type])
  showTimeDialog.value = true
}

const isSelected = (day, section) => {
  return tempSelection.value.has(JSON.stringify([day, section]))
}

const toggleTime = (day, section) => {
  const key = JSON.stringify([day, section])
  const newSet = new Set(tempSelection.value)
  if (newSet.has(key)) {
    newSet.delete(key)
  } else {
    newSet.add(key)
  }
  tempSelection.value = newSet
}

const confirmTimeSelection = () => {
  if (currentPickerType.value === 'forbidden') {
    config.forbidden = new Set(tempSelection.value)
  } else {
    config.allowed = new Set(tempSelection.value)
  }
  showTimeDialog.value = false
  console.log(config)
  console.log(forbiddenDisplay)
}

const selectedLabels = (day, section) => {
  return tempSelection.value.has(JSON.stringify([day, section])) ? '✓' : ''
}

const clearConfig = () => {
  config.forbidden = new Set()
  config.allowed = new Set()
  config.courseCodes = []
}

// 更新教学班代码列表
const updateCourseCodes = values => {
  config.courseCodes = values.map(item => item[item.length - 1])

  courseOptions.value.forEach(item => {
    item.children.forEach(child => {
      child.disabled = false
    })
  })

  // 修改相同教学班代码的 disabled 属性
  for (const _values of values) {
    for (const item of courseOptions.value) {
      if (item.value === _values[0]) {
        for (const child of item.children) {
          if (child.value !== _values[1]) {
            child.disabled = true
          }
        }
      }
    }
  }
}

function extractUniqueCourseNames(jsonData) {
  const courseNames = []

  // 遍历所有时间段
  for (const schedule of jsonData.schedules) {
    // 检查一周的每一天
    const daysOfWeek = [
      schedule.monday,
      schedule.tuesday,
      schedule.wednesday,
      schedule.thursday,
      schedule.friday,
      schedule.saturday,
      schedule.sunday,
    ]

    for (const dayCourses of daysOfWeek) {
      // 跳过空值和非数组的情况
      if (Array.isArray(dayCourses)) {
        for (const course of dayCourses) {
          courseNames.push(course.course_name)
        }
      }
    }
  }

  // 使用 Set 去重并返回数组
  return [...new Set(courseNames)]
}
</script>

<style lang="scss" scoped>
.ele-body {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  background-color: #fff;
}

table {
  width: 100%;
  background-color: #fff;
  border-color: #e3e8ee;
  text-align: center;
  border-radius: 4px;
  border-top: 1px solid #e3e8ee;
  border-left: 1px solid #e3e8ee;
  table-layout: fixed; /* 固定表格布局 */
}

th,
td {
  border-bottom: 1px solid #e3e8ee;
  border-right: 1px solid #e3e8ee;
  text-align: center;
  box-sizing: border-box;
  padding: 6px;
}

th {
  height: 30px;
  background-color: #f3f3f3;
  color: #525252;
  font-weight: bold;
}

.time {
  background: #f7f7f7;
  color: #707070;
  font-weight: bold;
  white-space: pre-line; /* 支持换行符 */
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  box-sizing: border-box;
  padding: 10px;

  .center {
    display: flex;
    justify-content: center;
    align-items: center;

    p {
      font-size: 20px;
      margin: 0 30px;
    }
  }
}

.course-item {
  display: flex;
  justify-content: center;
  flex-direction: column;
  gap: 6px;
  align-items: center;
  background: #318bff;
  min-height: 50px;
  border-radius: 4px;
  box-sizing: border-box;
  padding: 10px 0;

  p {
    color: #fff;
    white-space: pre-line; // 保留换行符
  }
}

/* 固定列宽 */
.fixed-width {
  width: 120px; /* 根据需要调整宽度 */
  height: 80px;
  font-size: 15px;
}

.fixed-width-header {
  width: 120px; /* 根据需要调整宽度 */
  height: 50px;
}

.not-current-week {
  opacity: 0.2; // 或者 background-color: #f0f0f0; 等样式
}

.schedule-controls {
  .control-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;

    .el-radio-group {
      display: flex;
      justify-content: center;
      width: 240px; // 设置固定宽度

      :deep(.el-radio-button__inner) {
        padding: 8px 15px;
      }

      :deep(.el-radio-button) {
        flex: 1; // 让按钮平分宽度

        .el-radio-button__inner {
          width: 100%; // 让按钮内容占满分配的空间
        }
      }
    }

    .el-button {
      width: 240px; // 与radio-group相同宽度
    }
  }
}

.popover-content {
  h4 {
    margin: 0;
    font-size: 16px;
    color: #333;
  }
  hr {
    margin: 5px 0;
    border: none;
    border-top: 1px solid #eee;
  }
  p {
    margin: 5px 0;
    font-size: 14px;
    color: #555;
  }
}

.time-grid {
  display: flex;
  flex-direction: column;
  border: 1px solid #ebeef5;
}

.header-row,
.time-row {
  display: flex;
  height: 50px;
}

.header-cell,
.row-header {
  flex: 1;
  min-width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ebeef5;
  background: #f5f7fa;
  font-weight: bold;
  white-space: pre-line; /* 支持换行符 */
  font-size: 12px;
  text-align: center;
}

.time-cell {
  flex: 1;
  min-width: 80px;
  border: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.time-cell:hover {
  background-color: #f0f9eb;
}

.time-cell.selected {
  background-color: #409eff;
  color: white;
}

.rainbow-border {
  --borderWidth: 12px;
  --bRadius: 5px;
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 0;
  overflow: hidden;
  // padding: 2rem;
  z-index: 0;
  border-radius: --bRadius;

  &::after,
  &::before {
    box-sizing: border-box;
  }

  &::before {
    content: ''; // 伪元素
    position: absolute; // 绝对定位
    left: -150%; // 左偏移50%
    top: -150%; // 上偏移50%
    width: 400%; // 宽度200%
    height: 400%; // 高度200%
    z-index: -2; // 层级-2
    background: conic-gradient(#399953, #fbb300, #d53e33, #377af5, #399953);
    animation: rotate 3s linear infinite;
    @keyframes rotate {
      100% {
        transform: rotate(1turn);
      }
    }
  }
  &::after {
    content: '';
    position: absolute;
    z-index: -1;
    left: calc(var(--borderWidth) / 2);
    top: calc(var(--borderWidth) / 2);
    width: calc(100% - var(--borderWidth));
    height: calc(100% - var(--borderWidth));
    // background: var(--dynamic-bg-color);
    border-radius: --bRadius;
    /*  这一行是为了方便查看原来的样子的 */
    // animation: opacityChange 3s infinite alternate;
  }
  @keyframes opacityChange {
    50% {
      opacity: 1;
    }
    100% {
      opacity: 0.5;
    }
  }
}
</style>
